from django.shortcuts import render

# Create your views here.
from django.core.paginator import Paginator
from .models import Cate,Good
from rest_framework.views import APIView
from .ser import CateSerializers,GoodSerializers
from rest_framework.response import Response
class Cateadd(APIView):
    def post(self,request):
        name = request.data
        a = CateSerializers(data=name)
        a.is_valid()
        a.save()
        return Response({'msg':'添加成功','code':200})

class Addgood(APIView):
    def get(self,request):
        name = Cate.objects.all()
        aname = CateSerializers(name,many=True)
        return Response(aname.data)
    def post(self,requset):
        a = GoodSerializers(data=requset.data)
        print(a)
        if a.is_valid():
            a.save()
            return Response({'msg':'添加成功',"code":200})
        else:
            print(a.errors)
class Page(APIView):
    def get(self, request):
        # 获取前端数据
        a = request.query_params['page_id']
        # 获取数据库数据
        b = Cate.objects.all()
        # 创建分页
        c = Paginator(b, 2)
        # 获取分页页码h
        d = [i for i in c.page_range]
        # 获取当前页的数据
        e = c.page(a)
        # 获取最后一页的页码数
        g = c.num_pages
        # 序列化
        f = CateSerializers(e, many=True)
        return Response(data={'page_list': d, 'cate_list': f.data,'c':g})
class GoodShow(APIView):

    def get(self,request):
        data = request.query_params
        # print(data)

        hhhh = Cate.objects.get(id=data["id"])
        hhh = Good.objects.filter(cate=hhhh).all()
        hh = GoodSerializers(hhh,many=True)
        h = hh.data
        print(h)
        return Response(data=h,status=200)
    def delete(self,request):
        id = request.data.get('id')
        a = Good.objects.filter(id=id)
        a.delete()
        return Response({'msg':'删除成功','code':200})